package pers.jsan.litheopen.security.config.request;


import com.baomidou.mybatisplus.core.toolkit.StringUtils;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * request/response封装拦截器。
 * 方便获取入参出参
 */
public class BodyReaderFilter implements Filter {

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        ServletRequest requestWrapper=null;
        ServletResponse responseWrapper=null;
        if(request instanceof HttpServletRequest) {
            requestWrapper=new BodyReaderHttpServletRequestWrapper((HttpServletRequest)request);
        }
        if(response instanceof HttpServletResponse){
            responseWrapper=new BodyReaderHttpServletResponseWrapper((HttpServletResponse)response);
        }
        chain.doFilter(
                requestWrapper==null?request:requestWrapper,
                responseWrapper==null?response:responseWrapper
        );
        if(responseWrapper!=null){
            String result = ((BodyReaderHttpServletResponseWrapper)responseWrapper).getResult();
            if(StringUtils.isNotEmpty(result)){
                PrintWriter out = response.getWriter();
                out.write(result);
                out.flush();
                out.close();
            }
        }


    }

    @Override
    public void destroy() {
        // do nothing
    }
}
